<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PermissionNode;
use App\Models\Role;
use App\Models\FunctionModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PermissionAdminController extends Controller
{
    /**
     * 获取权限节点列表
     */
    public function getPermissionNodes(Request $request)
    {
        try {
            $query = PermissionNode::query();

            // 搜索
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('code', 'like', "%{$search}%")
                      ->orWhere('description', 'like', "%{$search}%");
                });
            }

            // 类型筛选
            if ($request->has('type')) {
                $query->where('type', $request->type);
            }

            // 状态筛选
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // 分页
            $perPage = $request->get('per_page', 15);
            $nodes = $query->orderBy('type')->orderBy('code')->paginate($perPage);

            return $this->paginate($nodes, '获取权限节点列表成功');
        } catch (\Exception $e) {
            return $this->error('获取权限节点列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建权限节点
     */
    public function createPermissionNode(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'code' => 'required|string|max:150|unique:permission_nodes',
                'name' => 'required|string|max:100',
                'type' => 'required|in:page,api,field',
                'resource' => 'nullable|string|max:200',
                'description' => 'nullable|string|max:500',
                'status' => 'required|in:active,inactive',
            ]);

            $node = PermissionNode::create($data);

            return $this->success($node, '创建权限节点成功', 201);
        } catch (\Exception $e) {
            return $this->error('创建权限节点失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新权限节点
     */
    public function updatePermissionNode(Request $request, PermissionNode $node)
    {
        try {
            $data = $this->validateRequest($request, [
                'code' => 'required|string|max:150|unique:permission_nodes,code,' . $node->id,
                'name' => 'required|string|max:100',
                'type' => 'required|in:page,api,field',
                'resource' => 'nullable|string|max:200',
                'description' => 'nullable|string|max:500',
                'status' => 'required|in:active,inactive',
            ]);

            $node->update($data);

            return $this->success($node, '更新权限节点成功');
        } catch (\Exception $e) {
            return $this->error('更新权限节点失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除权限节点
     */
    public function deletePermissionNode(PermissionNode $node)
    {
        try {
            // 检查是否有功能在使用此权限节点
            if ($node->functions()->count() > 0) {
                return $this->error('无法删除正在使用的权限节点', 422);
            }

            $node->delete();

            return $this->success(null, '删除权限节点成功');
        } catch (\Exception $e) {
            return $this->error('删除权限节点失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取角色的功能权限
     */
    public function getRoleFunctions(Request $request, Role $role)
    {
        try {
            $functions = $role->functions()
                ->with(['menu', 'permissionNodes'])
                ->orderBy('menu_id')
                ->orderBy('sort_order')
                ->get()
                ->groupBy('menu.code');

            return $this->success($functions, '获取角色功能权限成功');
        } catch (\Exception $e) {
            return $this->error('获取角色功能权限失败: ' . $e->getMessage());
        }
    }

    /**
     * 分配功能权限给角色
     */
    public function assignFunctionsToRole(Request $request, Role $role)
    {
        try {
            $data = $this->validateRequest($request, [
                'function_ids' => 'required|array',
                'function_ids.*' => 'integer|exists:functions,id',
            ]);

            DB::beginTransaction();

            // 移除现有的功能权限
            $role->functions()->detach();

            // 分配新的功能权限
            foreach ($data['function_ids'] as $functionId) {
                $role->functions()->attach($functionId, [
                    'auto_granted' => false,
                    'granted_by' => $request->user()->id,
                    'granted_at' => now(),
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
            }

            DB::commit();

            return $this->success(null, '分配功能权限成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('分配功能权限失败: ' . $e->getMessage());
        }
    }

    /**
     * 移除角色的功能权限
     */
    public function removeFunctionFromRole(Role $role, FunctionModel $function)
    {
        try {
            $role->functions()->detach($function->id);

            return $this->success(null, '移除功能权限成功');
        } catch (\Exception $e) {
            return $this->error('移除功能权限失败: ' . $e->getMessage());
        }
    }

    /**
     * 预览角色权限分配结果
     */
    public function previewRolePermissions(Request $request, Role $role)
    {
        try {
            $data = $request->validate([
                'function_ids' => 'array',
                'function_ids.*' => 'integer|exists:functions,id',
            ]);

            $functionIds = $data['function_ids'] ?? [];

            // 获取将要分配的功能
            $functions = FunctionModel::whereIn('id', $functionIds)
                ->with(['menu', 'permissionNodes'])
                ->get();

            // 统计权限信息
            $permissions = [
                'menus' => $functions->pluck('menu')->unique('id')->values(),
                'functions' => $functions,
                'permission_nodes' => $functions->pluck('permissionNodes')->flatten()->unique('id')->values(),
                'summary' => [
                    'total_menus' => $functions->pluck('menu')->unique('id')->count(),
                    'total_functions' => $functions->count(),
                    'total_permission_nodes' => $functions->pluck('permissionNodes')->flatten()->unique('id')->count(),
                ]
            ];

            return $this->success($permissions, '获取权限预览成功');
        } catch (\Exception $e) {
            return $this->error('获取权限预览失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取用户的功能权限列表
     */
    public function getUserPermissions(Request $request)
    {
        try {
            $user = $request->user();

            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            $permissions = [
                'functions' => $user->getFunctionPermissions(),
                'menus' => $user->getAccessibleMenus()->pluck('code')->toArray(),
                'dependencies' => $this->getFunctionDependencies($user),
            ];

            return $this->success($permissions, '获取用户权限成功');
        } catch (\Exception $e) {
            return $this->error('获取用户权限失败: ' . $e->getMessage());
        }
    }

    /**
     * 检查用户是否有指定功能权限
     */
    public function checkUserFunctionPermission(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'function_code' => 'required|string'
            ]);

            $user = $request->user();

            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            $hasPermission = $user->hasFunctionPermission($data['function_code']);
            $canUse = $user->canUseFunction($data['function_code']);

            return $this->success([
                'function_code' => $data['function_code'],
                'has_permission' => $hasPermission,
                'can_use' => $canUse,
            ], '权限检查完成');
        } catch (\Exception $e) {
            return $this->error('权限检查失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取功能依赖关系
     */
    private function getFunctionDependencies(User $user): array
    {
        $functions = FunctionModel::with('menu')->get();
        $dependencies = [];

        foreach ($functions as $function) {
            $dependencies[$function->code] = collect($function->dependencies ?? [])
                ->map(function ($id) {
                    $depFunction = FunctionModel::find($id);
                    return $depFunction ? $depFunction->code : null;
                })
                ->filter()
                ->values()
                ->toArray();
        }

        return $dependencies;
    }
}
